package com.merry.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/scope")
public class ScopeController {

    @RequestMapping("/testServlet")
    public String testServlet(HttpServletRequest request){
        request.setAttribute("servletScope","hi,servlet!");
        return "scope";
    }

    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        ModelAndView modelAndView = new ModelAndView();
        //设置模型数据。
        modelAndView.addObject("servletScope","hi,modelAndView!");
        //设置视图名称。
        modelAndView.setViewName("scope");
        return modelAndView;
    }

    @RequestMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("servletScope","hi,model!");
        return "scope";
    }

    @RequestMapping("/testMap")
    public String testMap(Map<String,Object> map){
        map.put("servletScope","hello,map!");
        System.out.println(map.getClass().getName());
        return "scope";
    }

    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("servletScope","hi,modelMap!");
        return "scope";
    }

    @RequestMapping("/testSession")
    public String testSession(HttpSession session){
        session.setAttribute("sessionScope","hi,session!");
        return "scope";
    }

    @RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("contextScope","hi,servlet context");
        return "scope";
    }
}
